package bb.lanxing.activity.bluetooth;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.github.mikephil.charting.utils.Utils;

import androidx.annotation.RequiresApi;
import bb.lanxing.lib.devices.api.DeviceManager;
import bb.lanxing.lib.devices.ble.BleCons;
import bb.lanxing.network.MyHttpClient;
import gov.nist.core.Separators;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseDisplayActivity;
import bb.lanxing.calc.data.DisplayPoint;
import bb.lanxing.devices.utils.XZDeviceHelper;
import bb.lanxing.lib.devices.api.ConnectionListener;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.base.DeviceContext;
import bb.lanxing.lib.devices.utils.CadenceUtils;
import bb.lanxing.lib.devices.utils.DeviceVersionHelper;
import bb.lanxing.manager.RemoteSharedPreference;
import bb.lanxing.manager.SPConstant;
import bb.lanxing.model.database.Device;
import bb.lanxing.mvp.model.XOSSVortexServerFirmwareModel;
import bb.lanxing.util.Log;
import bb.lanxing.util.ui.BadgeView;
import bb.lanxing.view.BiciAlertDialogBuilder;
import java.text.DecimalFormat;
import java.util.Map;
import java.util.Objects;

import kotlinx.coroutines.DebugKt;
import rx.Subscriber;

public class SwitchableCadenceStatusActivity extends BaseDisplayActivity implements ConnectionListener {
    private final static String TAG = "SwitchableCadenceStatusActivity";
    private TextView batteryView;
    private TextView cadenceView;
    private Device device;
    private ImageView ivLogo;
    private LinearLayout llCadence;
    private LinearLayout llSpeed;
    private RadioButton radioCadence;
    private RadioGroup radioGroupType;
    private RadioButton radioSpeed;
    private TextView speedView;
    private CountDownTimer swtichModeTimer;
    private TextView tvManufacture;
    private TextView tvModel;
    private TextView tvVersion;
    private TextView unbindBtn;
    private TextView wheelLengthView;
    private RelativeLayout wheelSettingView;
    private XOSSVortexServerFirmwareModel xossVortexServerFirmwareModel;
    private DecimalFormat decimalFormat = new DecimalFormat("0.00");
    private Handler handler = new Handler();
    private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(getClass() + " onReceive action = " + action);
            switch (Objects.requireNonNull(action)) {
                case BleCons.ACTION_DEVICE_INFORMATION -> {
                    if (intent.getIntExtra("EXTRA_DEVICE_TYPE", 0) != SmartDevice.TYPE_VORTEX_CADENCE) {
                        return;
                    }
                    String stringExtra = intent.getStringExtra("EXTRA_DEVICE_INFORMATION");
                    if (stringExtra != null) {
                        setUIVersion(stringExtra);
                    }
                    String stringExtra2 = intent.getStringExtra("EXTRA_MODEL");
                    if (stringExtra2 != null) {
                        setUIModel(stringExtra2);
                        if (device != null) {
                            DeviceVersionHelper.setModelVersion(context, device.getAddress(), stringExtra2);
                        }
                    }
                    String stringExtra3 = intent.getStringExtra("EXTRA_EXTRA_MANUFACTURE");
                    if (stringExtra3 != null) {
                        setUIManufacture(stringExtra3);
                    }
                    checkFirmware(tvVersion.getText().toString(), tvModel.getText().toString());
                    int cscFeature = intent.getIntExtra("EXTRA_CSC_FUTURE", -1);
                    Log.d(TAG, "onReceive cscFeature=" + cscFeature);
                    if (cscFeature != -1) {
                        setUpType();
                    }
                }

                case BleCons.ACTION_READ_DEVICE_INFORMATION_RESULT -> {
                    String stringExtra4 = intent.getStringExtra(BleCons.EXTRA_MANUFACTURE);
                    String stringExtra5 = intent.getStringExtra(BleCons.EXTRA_FIRMWARE_VERSION);
                    String stringExtra6 = intent.getStringExtra(BleCons.EXTRA_MODEL);
                    int intExtra = intent.getIntExtra(BleCons.EXTRA_BATTERY, 0);
                    if (stringExtra4 == null || stringExtra5 == null || stringExtra6 == null
                            || stringExtra4.isEmpty() || stringExtra5.isEmpty() || stringExtra6.isEmpty()) {
                        requestDeviceInfo();
                    }
                    if (intExtra == 0) {
                        requestBattery();
                    } else {
                        setUIBattery(intExtra);
                    }
                    if (stringExtra4 != null) {
                        setUIManufacture(stringExtra4);
                    }
                    if (stringExtra5 != null) {
                        setUIVersion(stringExtra5);
                    }
                    if (stringExtra6 != null) {
                        setUIModel(stringExtra6);
                    }
                    checkFirmware(stringExtra5, stringExtra6);
                }

                case BleCons.ACTION_BATTERY -> {
                    if (intent.getIntExtra(BleCons.EXTRA_DEVICE_TYPE, 0) == SmartDevice.TYPE_VORTEX_CADENCE) {
                        setUIBattery(intent.getIntExtra(BleCons.EXTRA_BATTERY, 0));
                    }
                }
                default -> {
                }
            }
        }
    };

    private void uploadDeivceInfo() {
    }

    @RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_switchable_cadence_status);
        bindView(getWindow().getDecorView());
        setupActionBar(true);
        setTitle(getString(R.string.device_vortex_title));
        XZDeviceHelper.registerConnectionStateListener(this);
        registerReceiver();
        Device byAddress = Device.getByAddress(getIntent().getStringExtra(BleCons.EXTRA_DEVICE_ADDRESS));
        device = byAddress;
        if (byAddress == null) {
            finish();
            return;
        }
        this.wheelSettingView.setOnClickListener(view -> showWheelSettingDialog());

        this.unbindBtn.setOnClickListener(view -> unBoundDeviceConfirm());
        if (device.getDeviceNumber() == 0) {
            uploadDeivceInfo();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        this.handler.postDelayed(() -> {
            float f = RemoteSharedPreference.getInstance().getFloat(SPConstant.KEY_WHEEL_LENGTH, 2.171f);
            TextView textView = wheelLengthView;
            textView.setText(((int) (f * 1000.0f)) + " mm");
            if (BadgeView.shouldShowByFirstTime(wheelLengthView)) {

                new BadgeView(getActivity()).setAutoHide(true).setBadgeMargin(0, 0, 15, 0)
                        .setHideOnNull(false)
                        .setOnHideListener(() -> BadgeView.setNotFirst(wheelLengthView))
                        .toTargetView(wheelLengthView);
            }
        }, 200L);
        if (device != null) {
            if (XZDeviceHelper.isConnected(SmartDevice.TYPE_VORTEX_CADENCE)
                    || XZDeviceHelper.isConnecting(device.getAddress())) {
                setUpType();
                requestBattery();
                readDeviceInfo();
            } else {
                XZDeviceHelper.connect(device);
            }
        }
    }

    public void unBoundDeviceConfirm() {
        new BiciAlertDialogBuilder(this)
                .setTitle(R.string.st_forget_sensor)
                .setMessage(R.string.st_are_you_sure_unbind)
                .setPositiveButton(R.string.mine_profile_dialog_btn_unbind, (dialogInterface, i) -> {
                    if (device.getDeviceNumber() > 0) {
                        MyHttpClient.deleteDevice(device.getDeviceNumber());
                    }
                    DeviceContext.getDeviceProvider().removeByTypeAndFlag(
                            device.getType(), device.getFlags());
                    DeviceContext.getDeviceManager().disconnect(device.getAddress());
                    DeviceContext.startAndRefreshAutoConnector();
                    finish();
                })
                .setNegativeButton(R.string.str_sync_cancel, (dialogInterface, i) -> {
                }).show().setCanceledOnTouchOutside(true);
    }

    public void setUpType() {
        device = Device.getByAddress(device.getAddress());
        this.radioGroupType.setOnCheckedChangeListener(null);
        if (device.getType() == SmartDevice.TYPE_VORTEX_CADENCE) {
            Log.d(TAG, "setUpType flags=" + device.getFlags());
            if (CadenceUtils.hasWheelRevolution(device.getFlags())) {
                this.llSpeed.setVisibility(View.VISIBLE);
                this.llCadence.setVisibility(View.GONE);
                this.radioSpeed.setChecked(true);
                this.wheelSettingView.setVisibility(View.VISIBLE);
                this.ivLogo.setBackgroundResource(R.drawable.ic_default);
            } else if (CadenceUtils.hasCrankRevolution(device.getFlags())) {
                this.llCadence.setVisibility(View.VISIBLE);
                this.llSpeed.setVisibility(View.GONE);
                this.radioCadence.setChecked(true);
                this.wheelSettingView.setVisibility(View.GONE);
                this.ivLogo.setBackgroundResource(R.drawable.ic_default);
            }
        }
        this.radioGroupType.setOnCheckedChangeListener(new switchCandenceOrSpeed());
    }


    public class switchCandenceOrSpeed implements RadioGroup.OnCheckedChangeListener {
        switchCandenceOrSpeed() {
        }

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            boolean switchTo;
            boolean z = false;
            if (checkedId != SwitchableCadenceStatusActivity.this.radioSpeed.getId()) {
                if (checkedId == SwitchableCadenceStatusActivity.this.radioCadence.getId() && XZDeviceHelper.getSwitchableCadenceController() != null) {
                    switchTo = XZDeviceHelper.getSwitchableCadenceController().switchTo(1);
                    z = switchTo;
                }
//                z = false;
            } else {
                if (XZDeviceHelper.getSwitchableCadenceController() != null) {
                    switchTo = XZDeviceHelper.getSwitchableCadenceController().switchTo(0);
                    z = switchTo;
                }
//                z = false;
            }
            SwitchableCadenceStatusActivity.this.showLoadingDialog((CharSequence) "切换模式中，切换完成后需再次手动连接", false);
            boolean finalZ = z;
            SwitchableCadenceStatusActivity.this.swtichModeTimer = new CountDownTimer(3000L, 3000L) {
                @Override
                public void onTick(long millisUntilFinished) {
                }

                @Override
                public void onFinish() {
                    if (finalZ) {
                        SwitchableCadenceStatusActivity.this.dismissLoadingDialog();
                        SwitchableCadenceStatusActivity.this.toast("切换成功，请重新连接设备");
                        SwitchableCadenceStatusActivity.this.device.delete();
                        SwitchableCadenceStatusActivity.this.radioGroupType.postDelayed(SwitchableCadenceStatusActivity.this::finish, 500L);
                        return;
                    }
                    SwitchableCadenceStatusActivity.this.toast("切换失败,请返回重试");
                    SwitchableCadenceStatusActivity.this.radioGroupType.setOnCheckedChangeListener((group2, checkedId2) -> {
                        SwitchableCadenceStatusActivity.this.toast("切换失败,请返回重试");
                        SwitchableCadenceStatusActivity.this.finish();
                    });
                    SwitchableCadenceStatusActivity.this.dismissLoadingDialog();
                }
            };
            SwitchableCadenceStatusActivity.this.swtichModeTimer.start();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        dismissLoadingDialog();
        CountDownTimer countDownTimer = this.swtichModeTimer;
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    public void requestBattery() {
        Device device = this.device;
        if (device == null || device.getAddress() == null) {
            return;
        }

        this.batteryView.postDelayed(() -> {
            Intent intent = new Intent(BleCons.ACTION_REQUEST_BATTERY);
            intent.putExtra(BleCons.EXTRA_DEVICE_TYPE, SmartDevice.TYPE_VORTEX_CADENCE);
            intent.putExtra(BleCons.EXTRA_DEVICE_ADDRESS, device.getAddress());
            sendOrderedBroadcast(intent, null);
        }, 1600L);
    }

    public void requestDeviceInfo() {
        Device device = this.device;
        if (device == null || device.getAddress() == null) {
            return;
        }
        Intent intent = new Intent(BleCons.ACTION_REQUEST_DEVICE_INFORMATION);
        intent.putExtra(BleCons.EXTRA_DEVICE_TYPE, SmartDevice.TYPE_VORTEX_CADENCE);
        intent.putExtra(BleCons.EXTRA_DEVICE_ADDRESS, device.getAddress());
        sendOrderedBroadcast(intent, null);
    }

    private void readDeviceInfo() {
        Device device = this.device;
        if (device == null || device.getAddress() == null) {
            return;
        }

        this.batteryView.postDelayed(() -> {
            if (device.getAddress() == null) {
                return;
            }
            Intent intent = new Intent(BleCons.ACTION_READ_DEVICE_INFORMATION);
            intent.putExtra(BleCons.EXTRA_DEVICE_TYPE, SmartDevice.TYPE_VORTEX_CADENCE);
            intent.putExtra(BleCons.EXTRA_DEVICE_ADDRESS, device.getAddress());
            sendOrderedBroadcast(intent, null);
        }, 1800L);
    }

    public void setUIBattery(int battery) {
        TextView textView = this.batteryView;
        textView.setText(battery + Separators.PERCENT);
    }

    public void setUIVersion(String version) {
        this.tvVersion.setText(version);
    }

    public void setUIManufacture(String manufacture) {
        this.tvManufacture.setText(manufacture);
    }

    public void setUIModel(String model) {
        this.tvModel.setText(model);
    }

    public void checkFirmware(String firmwareVersion, String model) {
        if (firmwareVersion == null || model == null || firmwareVersion.isEmpty()
                || model.isEmpty() || firmwareVersion.equals("- -") || model.equals("- -")) {
            return;
        }
//        XOSSVortexServerFirmwareModel xOSSVortexServerFirmwareModel = new XOSSVortexServerFirmwareModel(model);
        xossVortexServerFirmwareModel = new XOSSVortexServerFirmwareModel(model);
//        this.xossVortexServerFirmwareModel = xOSSVortexServerFirmwareModel;
        xossVortexServerFirmwareModel.subscribeFirmware(new subCheckFirmwareVersion(firmwareVersion));
        xossVortexServerFirmwareModel.requestFirmwareVersion(getActivity());
    }

    public class subCheckFirmwareVersion extends Subscriber<Map<String, String>> {
        final String firmwareVersion;

        @Override
        public void onCompleted() {
        }

        subCheckFirmwareVersion(String str) {
            firmwareVersion = str;
        }

        @Override
        public void onError(Throwable th) {
            th.printStackTrace();
        }

        @Override
        public void onNext(Map<String, String> map) {
            if (xossVortexServerFirmwareModel != null
                    && DeviceVersionHelper.isNeedUpdate(firmwareVersion, xossVortexServerFirmwareModel.getFirmwareVersionName())) {
                new BadgeView(getActivity())
                        .setAutoHide(true)
                        .setHideOnNull(false)
                        .setOnHideListener(null)
                        .toTargetView(tvVersion);

                tvVersion.setOnClickListener(view -> {
//                    Intent intent = new Intent(getActivity(), SprintFirmwareUpdateActivity.class);
//                    intent.putExtra(SprintFirmwareUpdateActivity.EXTRA_IS_OFFLINE_MODE, false);
//                    intent.putExtra("EXTRA_DEVICE_ADDRESS", device.getAddress());
//                    intent.putExtra("EXTRA_DEVICE_TYPE", device.getType());
//                    startActivity(intent);
                });
            }
        }
    }

    @Override
    public void onDestroy() {
        BroadcastReceiver broadcastReceiver = this.broadcastReceiver;
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
        XZDeviceHelper.unregisterConnectionStateListener(this);
        super.onDestroy();
    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleCons.ACTION_BATTERY);
        intentFilter.addAction(BleCons.ACTION_DEVICE_INFORMATION);
        intentFilter.addAction(BleCons.ACTION_CADENCE_DATAS);
        intentFilter.addAction(BleCons.ACTION_PRESSURE_DATAS);
        intentFilter.addAction(BleCons.ACTION_READ_DEVICE_INFORMATION_RESULT);
        registerReceiver(this.broadcastReceiver, intentFilter, Context.RECEIVER_EXPORTED);
    }

    public void showWheelSettingDialog() {
        new BiciAlertDialogBuilder(this)
                .setItems(new String[]{getString(R.string.mine_wheel_setting_dialog_item_custom),
                        getString(R.string.mine_wheel_setting_dialog_item_check_table)},
                        (dialogInterface, i) -> {
                            Intent intent = new Intent(this, WheelLengthSetting.class);
                            intent.putExtra("auto", i != 0);
                            startActivity(intent);
                        }).show();
    }

    @Override
    protected void onRefreshUI(DisplayPoint displayPoint) {
        this.cadenceView.setText(String.valueOf(displayPoint.getCadence(0)));
        Log.d(TAG, "getSpeed=" +displayPoint.getSpeed(Utils.DOUBLE_EPSILON));
        Log.d(TAG, "getCadence=" +displayPoint.getCadence(0));
        this.speedView.setText(this.decimalFormat.format(displayPoint.getSpeed(Utils.DOUBLE_EPSILON) * 3.6d));
    }

    @Override
    public void onConnectionStateChanged(SmartDevice smartDevice, int i, int i2) {
        if (smartDevice.getType() == SmartDevice.TYPE_VORTEX_CADENCE
                && device != null && smartDevice.getAddress().equals(device.getAddress())) {
            if (i == DeviceManager.STATE_CONNECTED) {
                requestBattery();
            } else if (i == DeviceManager.STATE_DISCONNECTED){
                finish();
            }
        }
    }

    private void bindView(View view) {
        speedView = view.findViewById(R.id.speedView);
        cadenceView = view.findViewById(R.id.cadenceView);
        batteryView = view.findViewById(R.id.batteryView);
        wheelSettingView = view.findViewById(R.id.wheelSettingView);
        wheelLengthView = view.findViewById(R.id.wheelLengthView);
        unbindBtn = view.findViewById(R.id.unbindBtn);
        llSpeed = view.findViewById(R.id.ll_speed);
        llCadence = view.findViewById(R.id.ll_cadence);
        radioSpeed = view.findViewById(R.id.radio_speed);
        radioCadence = view.findViewById(R.id.radio_cadence);
        radioGroupType = view.findViewById(R.id.radio_group);
        ivLogo = view.findViewById(R.id.logo);
        tvVersion = view.findViewById(R.id.versionName);
        tvModel = view.findViewById(R.id.modelName);
        tvManufacture = view.findViewById(R.id.manufactureName);
    }
}
